package org.jeecgframework.core.util;

/*import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;*/

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by 大伟 on 2016/12/22.
 * Description
 */
public class ImageUtils {

    private static final String INCLUDE_EXT = "jpg,jpeg,png,bmp";

    public static boolean checkExt(String ext){
        if(StringUtil.isEmpty(ext)){
            return false;
        }
        if(INCLUDE_EXT.contains(ext) || INCLUDE_EXT.toUpperCase().contains(ext)){
            return true;
        }
        return false;
    }

    public static String getExt(String fileName){
        if(StringUtil.isEmpty(fileName)){
            return "";
        }else{
            int idx = fileName.indexOf(".");
            if(idx >= 0){
                return fileName.substring(idx);
            }
        }
        return "";
    }

    public static void compress(File imgFile,File destFile){
        if(null == imgFile){
            return;
        }
        if(!imgFile.exists()){
            return;
        }
        String ext = getExt(imgFile.getName());
        try{
            Image img = ImageIO.read(imgFile);
            int w = img.getWidth(null);
            int h = img.getHeight(null);
            BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );

            /*image.getGraphics().drawImage(img.getScaledInstance(w, h, Image.SCALE_FAST), 0, 0, null); // 绘制缩小后的图
            FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
            // 可以正常实现bmp、png、gif转jpg
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(image); // JPEG编码*/
//            out.close();

        }catch(Exception e){
            //todo 处理异常信息
        }
    }

}
